//
//  YDOAApplyVC.swift
//  YDOAProduct
//
//  Created by YDWY on 2017/5/31.
//  Copyright © 2017年 Allen. All rights reserved.
//

import UIKit
import HandyJSON


class YDOAApplyVC: UITableViewController {
    
    
    let  data = [
        ["id":"0","proposer":"曾诚","goods":"黑色签字笔","price":"1.5","status":"0"],
        ["id":"0","proposer":"张威","goods":"黑色签字笔","price":"1.5","status":"0"],
        ["id":"0","proposer":"占益民","goods":"黑色签字笔","price":"1.5","status":"0"],
        ["id":"0","proposer":"张云霄","goods":"黑色签字笔","price":"1.5","status":"0"],
        ["id":"0","proposer":"伏丹","goods":"黑色签字笔","price":"1.5","status":"0"],
        ["id":"0","proposer":"任金玲","goods":"黑色签字笔","price":"1.5","status":"0"],
        ["id":"0","proposer":"张赛","goods":"黑色签字笔","price":"1.5","status":"0"],
        ["id":"0","proposer":"孙萌","goods":"黑色签字笔","price":"1.5","status":"0"],
        ["id":"0","proposer":"李倩倩","goods":"黑色签字笔","price":"1.5","status":"0"],
        ["id":"0","proposer":"陈莹","goods":"黑色签字笔","price":"1.5","status":"0"],
        
        
        ]
    

    
    
    lazy var statusArr : Array  = Array<Int>() //保存所有头部的状态
    lazy var headerViews : Array = Array<UIView>() //保存所有头部视图
    lazy var dataSource : Array = Array<YDOAStayModel>()//数据源
    
    

    lazy var headerView = { () -> UIView in
        let view1 = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 30))
        let lab = UILabel.ym_lable(text: "申请人qq", fontSize: 15, color: UIColor.black)
        lab.frame = CGRect(x: 0, y: 0, width: ScreenWidth / 3, height: 30)
        lab.textAlignment = .center
        lab.isUserInteractionEnabled = true
        view1.addSubview(lab)
        let  lab1 = UILabel.ym_lable(text: "申请物品", fontSize: 15, color: UIColor.black)
        lab1.frame = CGRect(x: ScreenWidth / 3, y: 0, width: ScreenWidth / 3, height: 30)
        lab1.textAlignment = .center
        lab1.isUserInteractionEnabled = true
        view1.addSubview(lab1)
        let  lab2 = UILabel.ym_lable(text: "价格", fontSize: 15, color: UIColor.black)
        lab2.frame = CGRect(x: (ScreenWidth / 3) * 2, y: 0, width: ScreenWidth / 3, height: 30)
        lab2.textAlignment = .center
        lab2.isUserInteractionEnabled = true
        view1.addSubview(lab2)
        view1.backgroundColor = UIColor.lightGray
        return view1
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "申请管理"
        setUpHeaderView()
        
        
        self.navigationController?.navigationBar.isHidden = false
        //设置NavBar  右边的额按钮
//        let rightItem =  UIButton(type: .custom)
//        rightItem.titleLabel?.text = "紧急行政物资"
//        rightItem.titleLabel?.textColor = UIColor.red
//        rightItem.frame = CGRect(x: 0, y: 0, width: 80, height: 30)
//        rightItem.addTarget(self, action: #selector(urgency), for: .touchUpInside)
//        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightItem)
        let rightItem = UIBarButtonItem(title: "紧急行政物资", style: UIBarButtonItemStyle.plain, target: self, action: #selector(urgency))
        rightItem.tintColor = UIColor.red

        navigationItem.rightBarButtonItem = rightItem
        
        
        tableView.contentInset =  UIEdgeInsetsMake(0, 0, 64, 0);
        
        tableView.backgroundView = UIImageView(image: UIImage(named: "timg"))
        
        
        tableView.register(  UINib(nibName: "YDStaycheckCell", bundle: nil), forCellReuseIdentifier: "YDStaycheckCell")
        
        getData()
        
      
        headerViews.removeAll()
        tableView.reloadData()
        
    }
    
    private func getData(){
        for dict in data {
            guard let model = JSONDeserializer<YDOAStayModel>.deserializeFrom(dict: dict as NSDictionary?) else {
                return
            }
            
            dataSource.append(model)
        }
        for _ in 0..<dataSource.count {
            statusArr.append(0)
        }
        
    }

    
    
    
    private func setUpHeaderView(){
        let view1 = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 40))
        let lab = UILabel.ym_lable(text: "申请人", fontSize: 15, color: UIColor.black)
        lab.frame = CGRect(x: 0, y: 0, width: ScreenWidth / 3, height: 40)
        lab.textAlignment = .center
        lab.isUserInteractionEnabled = true
        view1.addSubview(lab)
        let  lab1 = UILabel.ym_lable(text: "申请物品", fontSize: 15, color: UIColor.black)
        lab1.frame = CGRect(x: ScreenWidth / 3, y: 0, width: ScreenWidth / 3, height: 40)
        lab1.textAlignment = .center
        lab1.isUserInteractionEnabled = true
        view1.addSubview(lab1)
        let  lab2 = UILabel.ym_lable(text: "申请时间", fontSize: 15, color: UIColor.black)
        lab2.frame = CGRect(x: (ScreenWidth / 3) * 2, y: 0, width: ScreenWidth / 3, height: 40)
        lab2.textAlignment = .center
        lab2.isUserInteractionEnabled = true
        view1.addSubview(lab2)
        view1.backgroundColor = UIColor.lightGray
        let  lineView = UIView(frame: CGRect(x: 0, y: 39, width: ScreenWidth, height: 1))
        lineView.backgroundColor = UIColor.ym_colorWithRGB(r: 222, g: 222, b: 222)
        view1.addSubview(lineView)
        tableView.tableHeaderView = view1
        //tableView.h.addSubview(view1)
        
        
        //底部视图
        
        let  footView = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 64))
        footView.backgroundColor = UIColor.clear
        
        let  applyBtn = UIButton.ym_createButton(title: "发 起 申 请", fontSize: 16, normalColor: .white, highlightedColor: .black, backgroundImageName: nil)
        applyBtn.frame = CGRect(x: 20, y: 20, width: ScreenWidth - 40, height: 30)
        applyBtn.backgroundColor = UIColor(27, 142, 148)
        applyBtn.layer.cornerRadius = 8
        applyBtn.layer.masksToBounds = true
        applyBtn.addTarget(self, action: #selector(applyBtnClick), for: .touchUpInside)
        
        
        footView.addSubview(applyBtn)
        tableView.tableFooterView = footView
        
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return (dataSource.count)
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        if statusArr[section] == 0 {
            return 0
        }
        return 1
    }
    
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        //删除所有视图
        let model = dataSource[section]
        
        let view1 = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 40))
        
        if model.status == 0{
            view1.backgroundColor = UIColor.white
        }else if model.status == 1{
            view1.backgroundColor = UIColor.ym_colorWithRGB(r: 56, g: 168, b: 71)
        }else{
            view1.backgroundColor = UIColor.red
        }
        
        let lab = UILabel.ym_lable(text:model.proposer!, fontSize: 15, color: UIColor.black)
        lab.frame = CGRect(x: 0, y: 0, width: ScreenWidth / 3, height: 40)
        lab.textAlignment = .center
        lab.isUserInteractionEnabled = true
        view1.addSubview(lab)
        let  lab1 = UILabel.ym_lable(text: model.goods!, fontSize: 15, color: UIColor.black)
        lab1.frame = CGRect(x: ScreenWidth / 3, y: 0, width: ScreenWidth / 3, height: 40)
        lab1.textAlignment = .center
        lab1.isUserInteractionEnabled = true
        view1.addSubview(lab1)
        let  lab2 = UILabel.ym_lable(text:model.price!, fontSize: 15, color: UIColor.black)
        lab2.frame = CGRect(x: (ScreenWidth / 3) * 2, y: 0, width: ScreenWidth / 3, height: 40)
        lab2.textAlignment = .center
        lab2.isUserInteractionEnabled = true
        view1.addSubview(lab2)
        view1.tag = 500 + section
        let tap = UITapGestureRecognizer(target: self, action: #selector(click))
        view1.addGestureRecognizer(tap)
        let  lineView = UIView(frame: CGRect(x: 0, y: 39, width: ScreenWidth, height: 1))
        lineView.backgroundColor = UIColor.ym_colorWithRGB(r: 222, g: 222, b: 222)
        view1.addSubview(lineView)
        

        if headerViews.count < statusArr.count{
            headerViews.append(view1)
        }
        
        return view1
        
    }
    
    @objc private func click(tap : UIGestureRecognizer){
        let tag = (tap.view?.tag)! - 500
        if statusArr[tag] == 0 {
            statusArr[tag] = 1
        }else{
            statusArr[tag] = 0
        }
        headerViews.removeAll()
        tableView.reloadData()
    }
    
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 40
    }
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
        
    }
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "YDStaycheckCell", for: indexPath) as? YDStaycheckCell  else {
            return YDStaycheckCell()
        }
        cell.backgroundColor = UIColor.clear
        cell.cellId = indexPath.section
        cell.selectionStyle = .none
        
        weak var weakSelf = self
        cell.callbackWithID = {(styleId : Int, cellId : Int) in
            
            YMLog.log(item: self.headerViews.count)
            
            //通过
            if styleId == 1 {
                
                let  bgview = weakSelf?.headerViews[(weakSelf?.dataSource.count)! - 1]
                let model = weakSelf?.dataSource[cellId]
                model?.status = 1
                weakSelf?.dataSource.remove(at: cellId)
                weakSelf?.dataSource.insert(model!, at:(weakSelf?.dataSource.count)! )
                //  weakSelf?.dataSource.insert(model!, at: (weakSelf?.dataSource.count - 1))
                weakSelf?.statusArr[cellId] = 0
                bgview?.backgroundColor = UIColor.ym_colorWithRGB(r: 56, g: 168, b: 71)
                for lab in (bgview?.subviews)! {
                    
                    if lab.isKind(of: UILabel.classForCoder()){
                        // let  lab1 = lab as? UILable
                        (lab as? UILabel)?.textColor = UIColor.white
                    }
                }
                tableView.reloadData()
                
            }else{//未通过
                let  bgview = self.headerViews[(weakSelf?.dataSource.count)! - 1]
                let model = weakSelf?.dataSource[cellId]
                model?.status = 2
                weakSelf?.dataSource.remove(at: cellId)
                weakSelf?.dataSource.insert(model!, at:(weakSelf?.dataSource.count)! )
                bgview.backgroundColor = UIColor.red
                for lab in bgview.subviews {
                    if lab.isKind(of: UILabel.classForCoder()) {
                        (lab as? UILabel)?.textColor = UIColor.white
                    }
                }
                weakSelf?.statusArr[cellId] = 0
                tableView.reloadData()
            }
        }
        
        return cell

    }

}



//

extension YDOAApplyVC {

    
    //紧急物资申请
    @objc fileprivate func  urgency(){
        YMLog.log(item: "紧急行政物资申请")
        let vc =  YDOAApplyPresentVC()
        vc.type = "紧急"
        vc.modalPresentationStyle = .overCurrentContext //模态视图的展现形式
        vc.view.backgroundColor = UIColor(white: 0.3, alpha: 0.7) //视图的背景颜色
        
        self.present(vc, animated: true, completion: {
            
        })
        

        
        
    }
    
    
    @objc fileprivate func applyBtnClick(){
        YMLog.log(item: "发起申请")
        let vc =  YDOAApplyPresentVC()
        vc.type = "普通"
        vc.modalPresentationStyle = .overCurrentContext //模态视图的展现形式
        vc.view.backgroundColor = UIColor(white: 0.3, alpha: 0.7) //视图的背景颜色
        
        vc.callBack = {(type : Int) in
            switch type {
                //物品申请
            case 0:
                self.navigationController?.pushViewController(YDOAApplyDetialVC(), animated: true)
                //费用申请
            case 1:
                self.navigationController?.pushViewController(YDOAApplyChargeVC(), animated: true)
            default:
                break
            }
        }
        
        self.present(vc, animated: true, completion: {
            
        })

    }
    


}


